package com.example.demo.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.demo.domain.entity.Notice;
import com.example.demo.domain.entity.ProblemFile;
import com.example.demo.dto.NoticeDto;
import com.example.demo.service.NoticeService;
import com.example.demo.mapper.NoticeMapper;
import com.example.demo.utils.ValidatorUtil;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.File;
import java.util.List;

/**
* @author 00774904
* @description 针对表【notice(公告)】的数据库操作Service实现
* @createDate 2023-09-27 16:13:14
*/
@Service
public class NoticeServiceImpl extends ServiceImpl<NoticeMapper, Notice>
    implements NoticeService{

    @Value("${problemFile.dir}")
    private String FILE_DIRECTORY;


    @Value("${notice.show.time}")
    private Integer SHOW_TIME;

    @Resource
    private NoticeMapper noticeMapper;

    @Override
    public void createNotice(Notice notice){
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<Notice>();
        Long aLong = noticeMapper.selectCount(queryWrapper);
        Integer order = Integer.valueOf(Math.toIntExact(aLong));
        notice.setShowTime(SHOW_TIME);
        notice.setOrderNo(++order);
        noticeMapper.insert(notice);
    }

    @Override
    public int deleteFileById(String id) {
        Notice notice = noticeMapper.selectById(id);
        if (null != notice) {
            notice.getPath();
            File file = new File(FILE_DIRECTORY + notice.getPath());
            file.delete();
        }
        return noticeMapper.deleteById(notice);
    }

    @Override
    public List<Notice> queryNotice(NoticeDto noticeDto) {
        QueryWrapper<Notice> queryWrapper = new QueryWrapper<Notice>();
        if (!StringUtils.isEmpty(noticeDto.getName())){
            queryWrapper.eq("name",noticeDto.getName());
        }
        List<Notice> notices = noticeMapper.selectList(queryWrapper);
        return notices;
    }

    @Override
    public void updateNotice(NoticeDto noticeDto) {
        if (null == noticeDto.getId()){
            ValidatorUtil.require(noticeDto.getId(), "id");
        }
        Notice notice = BeanUtil.copyProperties(noticeDto, Notice.class);
        noticeMapper.updateById(notice);
    }
}




